#!/bin/bash
################################################################################
#  Copyright (C) 2015-2018 IQIYI All rights reserved.
# 
#  Author     : 王海斌
#  E-mail     : wanghaibin@qiyi.com
#  Version    :
#  Date       : Fri 30 Nov 2018 11:06:41 AM CST
#  Destription: 获取某个条件下最新启动的进程id
#
################################################################################
cd `dirname $0`

keyInfo="./test.sh" # 过滤的进程执行路径
proc_num=""   # 获取到的最新进程id

startTime=0

#获取进程的启动时间
function GetProcStartTime() 
{
    local PID=$1
    if [ -z ${PID} ]
    then
        echo "usage ${0} ${1} pid"
        return 0    
    fi
    local STARTTIME=$(awk '{print int($22 /100)}' /proc/$PID/stat)
    local UT=$(awk '{print int($1)}' /proc/uptime)
    local NOW=$(date +%s)
    startTime=$((NOW - (UT - STARTTIME)))
    echo "$PID=`date -d @$startTime`"
}

#获取最新进程的进程id
function GetLatestPid()
{
    proc_num_all=(`ps -ef |grep "${keyInfo}" |grep -v grep |awk '{print $2,$8}' |grep "/bin/bash" |awk '{print $1}'`)
    proc_num=${proc_num_all[@]}
    for tmpPid in "${proc_num_all[@]}"
    do
        oldTime=${startTime}
        echo $tmpPid
        GetProcStartTime ${tmpPid}
        if [ ${oldTime} -lt ${startTime} ]
        then
            proc_num=${tmpPid}
        fi
    done
}

GetLatestPid

echo "latest proc id=${proc_num}"
